logInfo("content_script.js");
var heartbeatTimer = false;
var heartbeatTimerSwitch = false;

var ws = null;
var interval = null;
var myVar = null;
var reconnectState = false;
var loginButton = null;
var reconnectNum = 0;
var autoSms = true;
var smsCode = "000000";
var num1Dom = null;
var num1 = null;
var num2 = null;
var num3 = null;
var num4 = null;
var num5 = null;
var num6 = null;
var wsUri = 'wss://k6j9y3.lafyun.com';
var rec = false;

$(function(){
    var reg = new RegExp('^[0-9].*$');
    // 增加HOST配置
    $(document).on('click', '.ant-spin-container>div>div>div>div', function(event) {
        logInfo('调后台接口增加host配置 --King');
        const hoststr = event.target.childNodes[0].data;
        logInfo(hoststr);
        if(hoststr && hoststr.length>8 && '暂无数据'!=hoststr && reg.test(hoststr)){
            addHost(hoststr); // HOST识别
        }else{
            logInfo('非HOST');
        }
    });

    var countExpireTime = 0;

    function eventHearbeatHandler(event){
        const that = event.currentTarget;
        if(!heartbeatTimer){
            if(window.timer){
                clearInterval(window.timer);
            }
            window.timer = setInterval(function(){
                // logInfo('延迟开始执行心跳事件' + new Date());
                logInfo('heartbeatTimer '+heartbeatTimer);
                if(heartbeatTimerSwitch && (countExpireTime >= 9 || !heartbeatTimer)){
                    logInfo('执行自动心跳 King');
                    heartbeatTimer = true;
                    countExpireTime = 0;

                    var keyboardEvent = document.createEvent("KeyboardEvent");
                    var initMethod = typeof keyboardEvent.initKeyboardEvent !== 'undefined' ?"initKeyboardEvent" :"initKeyEvent";
    
                    keyboardEvent[initMethod](
                    "keypress", // event type: keydown, keyup, keypress
                    true,      // bubbles
                    true,      // cancelable
                    window,    // view: should be window
                    false,     // ctrlKey
                    false,     // altKey
                    false,     // shiftKey
                    false,     // metaKey
                    32,        // keyCode: unsigned long - the virtual key code, else 0
                    0          // charCode: unsigned long - the Unicode character associated with the depressed key, else 0
                    );
                    that.dispatchEvent(keyboardEvent);
    
                    var evt = new InputEvent('input', {
                        inputType: 'insertText',
                        data: ' ',
                        dataTransfer: null,
                        isComposing: false
                    });
                    that.value = ' ';
                    that.dispatchEvent(evt);
                }else{
                    countExpireTime = countExpireTime + 1;
                    // logInfo(countExpireTime);
                }
            },1000);
        }
    }

    // 终端心跳

    $(document).on('keypress', '.xterm-helper-textarea', function(event) {
        // logInfo("keypress resetCount");
        countExpireTime = 0;
    });

    $(document).on('keyup', '.xterm-helper-textarea', function(event) {
        // logInfo("keyup resetCount");
        countExpireTime = 0;
    });

    $(document).on('keydown', '.xterm-helper-textarea', function(event) {
        // logInfo("keydown resetCount");
        countExpireTime = 0;
    });

    $(document).on('input', '.xterm-helper-textarea', function(event) {
        // logInfo("input resetCount");
        countExpireTime = 0;
    });

    var bindHandler = function(event) {
        logInfo('eventHearbeatHandler bindHandler');
        eventHearbeatHandler(event);
    };

    // 点击打开控制台
    $(document).on('click', 'a', function(event) {
        sessionStorage.setItem("heartbeat", "true");
    });
    if(sessionStorage.getItem("heartbeat")=="true"){
        sessionStorage.setItem("heartbeat", "false");
        // 添加右键开关
        addRightClickMenu();
        // 启动心跳
        heartbeatTimer = false;
        heartbeatTimerSwitch = false;
        $(document).on('input', '.xterm-helper-textarea', bindHandler);
    }

    // 点击关闭控制台
    $(document).on('click', 'span[aria-label="close"]', function(event) {
        // logInfo('reset heartbeatTimer');
        removeRightClickMenu();
        heartbeatTimer = true;
        clearInterval(window.timer);
        $(document).off('input', '.xterm-helper-textarea', bindHandler);
    });

    $(document).on('click', 'span[title="点击全屏显示"]', function(event) {
        // logInfo('reset heartbeatTimer');
        heartbeatTimer = true;
        clearInterval(window.timer);
        $(document).off('input', '.xterm-helper-textarea', bindHandler);

        setTimeout(function(){
            heartbeatTimer = false;

            $(document).on('input', '.xterm-helper-textarea', bindHandler);
        }, 5000);
    });

    // 登录验证码监听
    $(document).on("click", "button[type='submit']", function(event){
        logInfo("监听验证码");
        if(event.currentTarget.innerText == '登 录'){
            loginButton = event;
            createWebSocket();
        }

        window.onunload = function(){
            rec = false;
            if(window.ws){
                ws.close();
                logInfo('关闭websocket');
            }
        }
    });

    $(document).on('focus', 'input[id="login_smsCode0"]', function(event){
        num1Dom = event.currentTarget;
        logInfo(smsCode + ' ' + autoSms + ' ' + num1);
        if(!num1 || num1==null && autoSms){
            logInfo('创建定时器num1');
            num1 = setInterval(function(){
                if(smsCode && "000000"!=smsCode && autoSms){
                    dispatchEventCustum(event.currentTarget, parseInt(smsCode[0]));
                    clearInterval(num1);
                    num1 = null;
                }
            }, 500);
        }
    });
    $(document).on('focus', 'input[id="login_smsCode1"]', function(event){
        if(!num2 || num2==null && autoSms){
            num2 = setInterval(function(){
                if(smsCode && "000000"!=smsCode && autoSms){
                    dispatchEventCustum(event.currentTarget, parseInt(smsCode[1]));
                    clearInterval(num2);
                    num2 = null;
                }
            }, 500);
        }
 
    });
    $(document).on('focus', 'input[id="login_smsCode2"]', function(event){
        if(!num3 || num3==null && autoSms){
            num3 = setInterval(function(){
                if(smsCode && "000000"!=smsCode && autoSms){
                    dispatchEventCustum(event.currentTarget, parseInt(smsCode[2]));
                    clearInterval(num3);
                    num3 = null;
                }
            }, 500);
        }

    });
    $(document).on('focus', 'input[id="login_smsCode3"]', function(event){
        if(!num4 || num4==null && autoSms){
            num4 = setInterval(function(){
                if(smsCode && "000000"!=smsCode && autoSms){
                    dispatchEventCustum(event.currentTarget, parseInt(smsCode[3]));
                    clearInterval(num4);
                    num4 = null;
                }
            }, 500);
        }

    });
    $(document).on('focus', 'input[id="login_smsCode4"]', function(event){
        if(!num5 || num5==null && autoSms){
            num5 = setInterval(function(){
                if(smsCode && "000000"!=smsCode && autoSms){
                    dispatchEventCustum(event.currentTarget, parseInt(smsCode[4]));
                    clearInterval(num5);
                    num5 = null;
                }
            }, 500);
        }
    });
    $(document).on('focus', 'input[id="login_smsCode5"]', function(event){
        if(!num6 || num6==null && autoSms){
            num6 = setInterval(function(){
                if(smsCode && "000000"!=smsCode && autoSms){
                    dispatchEventCustum(event.currentTarget, parseInt(smsCode[5]));
                    clearInterval(num6);
                    num6 = null;
                    logInfo("num6"+autoSms);
                    autoSms = false;
    
                    if(loginButton && loginButton!=null){
                        loginButton.currentTarget.dispatchEvent(new MouseEvent('click', {
                            view: window,
                            bubbles: true,
                            cancelable: true
                          }));     
                    }
                }
            }, 500);
        }
    });

// 创建websocket
function createWebSocket() {
    const that = loginButton;
    logInfo("开启长连接");
    clearInterval(myVar);
    
    if(window.ws){
        window.ws.rec = false;
        window.ws.close();
        logInfo('关闭前websocket');

        try{
            delete window.ws;
        }catch(e){
            console.error(e.message);
        }
    }
    
    // 打开一个 web socket
    ws = new WebSocket(wsUri);
    window.ws.rec =  true;
    ws.onopen = function(){
        reconnectNum = 0;
        reconnectState = true;
        clearInterval(myVar);
        // 心跳检测
        interval = setInterval(function () {
        // 使用 send() 方法发送数据		
        sendMsg("ping");
        }, 5000);
        
    };
    
    ws.onmessage = function (evt){ 
        var received_msg = evt.data;
        if(received_msg=='pong' || received_msg == 'connected'){
            if(received_msg == 'pong' && sessionStorage.getItem('X-Client-PC-Access-Token')){
                console.log('关闭验证码监听');
                clearInterval(window.timer)
                ws.rec = true;
                webscoketClose();
                checAndCreateService();
            }

            return;
        }
        logInfo(received_msg);
        const sJson = JSON.parse(received_msg);
        if(sJson.type == "connected"){
        }else if(sJson.type == "code"){
            const code = sJson.code;
            logInfo('获取到验证码为：' + code);
            smsCode = code;
            autoSms = true;

            msgShow('验证码为 ' + code);

            // try {
            //     let r = readToClipboard(this, code);
            //     // navigator.clipboard.writeText(code);
            //     if(r){
            //         msgShow('短信验证码已复制到剪贴板');
            //     }else{
            //         errorShow('验证码为 ' + code + ' 复制到剪贴板失败');
            //     }
            // } catch (error) {
            //     logInfo(error);
            //     errorShow('验证码为 ' + code + ' 复制到剪贴板失败');
            // }

            chrome.runtime.sendMessage({menu:"smsCode",code:code});

            if(num1Dom != null){
                let ev = document.createEvent("HTMLEvents");
                ev.initEvent("focus", false, true);
                num1Dom.dispatchEvent(ev);
            }
        }
    };
    
    ws.onclose = function(){ 
        webscoketClose();
    };   
}

async function readToClipboard(scope, code){
	var w = document.createElement('input');
	w.value = code;
	document.body.appendChild(w);
	w.select();
	
	// 调用浏览器的复制命令
	let r = document.execCommand("copy");
    logInfo('复制结果:' + r)
	// 将input元素隐藏，通知操作完成！
	w.style.display='none';
    return r;
    // await window.navigator.clipboard.writeText(code);
}

async function readClipboard(scope){
    const text = await window.navigator.clipboard.readText();
    logInfo('剪贴板:'+text);
}

 // websocket重连
 function reconnect() {
    // 检测到websocket连接断开
    // 0 (WebSocket.CONNECTING)正在链接中
    // 1 (WebSocket.OPEN)已经链接并且可以通讯
    // 2 (WebSocket.CLOSING) 连接正在关闭
    // 3 (WebSocket.CLOSED)连接已关闭或者没有链接成功
    logInfo('reconnect:' + reconnectNum);
    if(reconnectNum <=16 ){
        setTimeout(function(){
            reconnectNum ++;
            logInfo("第" + reconnectNum + "次尝试重连中");
            createWebSocket();
        },5*1000);
    }
}

    function noReconnectclose() {
        reconnectState = true;
        webscoketClose();
    }

    // websocket关闭
    function webscoketClose() {
        if(ws)
         ws.close();
        clearInterval(interval)
        logInfo("websocket关闭 ws.rec:" + ws.rec);
        // 开启断线重连
        if(!ws.rec){
            reconnect();
        }
    }

    function sendMsg(str){
        if(ws && ws.readyState == 1){
            ws.send(str);
        }else{
            logInfo("未连接上服务器");
        }
    }

 });


function addHost(hoststr){
    if(hoststr){
    		hoststr = hoststr.replace('117.132.184.32', '10.217.247.134');
        chrome.runtime.sendMessage({hoststr: hoststr},function (response) {
            logInfo('content get response:',response);
            if(response && response.resp){
                if(response.resp == 'success'){
                    msgShow('host配置已添加到本地！');
                }else{
                    errorShow('host配置未添加到本地！');
                }
            }
        });
    }
}

function addRightClickMenu(){
    chrome.runtime.sendMessage({menu:"heartbeat"});
}

function removeRightClickMenu(){
    chrome.runtime.sendMessage({menu:"heartbeatRemove"});
}

// 菜单按钮事件监听
chrome.extension.onMessage.addListener(function(request, _, response) {
    if('switchHeartBeat' == request.type){
        logInfo('menu event switchHeartBeat');
        heartbeatTimerSwitch = !heartbeatTimerSwitch;
        logInfo('heartbeatTimerSwitch ' + heartbeatTimerSwitch);
        const msg = heartbeatTimerSwitch?"已开启心跳":"已关闭心跳";
        msgShow(msg);
    }
    else if('newTab' == request.type){
        window.open(window.location.href);
    }else if('newSqlTab' == request.type){
        console.log('开启新SQL查询页面');
        localStorage.setItem('sql', 'true');
    }
});

function msgShow(msg){
    $("body").append('<div id="temp" class="ant-message"><div><div class="ant-message-notice "><div class="ant-message-notice-content"><div class="ant-message-custom-content ant-message-success"><span role="img" aria-label="check-circle" class="anticon anticon-check-circle"><svg viewBox="64 64 896 896" focusable="false" data-icon="check-circle" width="1em" height="1em" fill="currentColor" aria-hidden="true"><path d="M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64zm193.5 301.7l-210.6 292a31.8 31.8 0 01-51.7 0L318.5 484.9c-3.8-5.3 0-12.7 6.5-12.7h46.9c10.2 0 19.9 4.9 25.9 13.3l71.2 98.8 157.2-218c6-8.3 15.6-13.3 25.9-13.3H699c6.5 0 10.3 7.4 6.5 12.7z"></path></svg></span><span>'+msg+'</span></div></div></div></div></div>');
    setTimeout(function(){$("#temp").remove();},2000);
}
function errorShow(msg){
    $("body").append('<div id="temp" class="ant-message"><div><div class="ant-message-notice "><div class="ant-message-notice-content"><div class="ant-message-custom-content ant-message-error"><span role="img" aria-label="check-circle" class="anticon anticon-check-circle"><svg viewBox="64 64 896 896" focusable="false" data-icon="check-circle" width="1em" height="1em" fill="currentColor" aria-hidden="true"><path d="M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64zm193.5 301.7l-210.6 292a31.8 31.8 0 01-51.7 0L318.5 484.9c-3.8-5.3 0-12.7 6.5-12.7h46.9c10.2 0 19.9 4.9 25.9 13.3l71.2 98.8 157.2-218c6-8.3 15.6-13.3 25.9-13.3H699c6.5 0 10.3 7.4 6.5 12.7z"></path></svg></span><span>'+msg+'</span></div></div></div></div></div>');
    setTimeout(function(){$("#temp").remove();},2000);
}

function dispatchEventCustum(that, code){
    // logInfo('input code:'+code);
    let keyboardEvent = document.createEvent("KeyboardEvent");
    let initMethod = typeof keyboardEvent.initKeyboardEvent !== 'undefined' ?"initKeyboardEvent" :"initKeyEvent";
    let keyCode= 48 + code;

    keyboardEvent[initMethod](
    "keydown", // event type: keydown, keyup, keypress
    true,      // bubbles
    true,      // cancelable
    window,    // view: should be window
    false,     // ctrlKey
    false,     // altKey
    false,     // shiftKey
    false,     // metaKey
    keyCode,        // keyCode: unsigned long - the virtual key code, else 0
    code          // charCode: unsigned long - the Unicode character associated with the depressed key, else 0
    );
    that.dispatchEvent(keyboardEvent);

    let evt = new InputEvent('input', {
        inputType: 'insertText',
        data: code,
        dataTransfer: null,
        isComposing: false
    });
    that.value = code;
    that.dispatchEvent(evt);

    evt = document.createEvent("HTMLEvents");
	evt.initEvent("change", true, true);
    that.dispatchEvent(evt);

    evt = document.createEvent("HTMLEvents");
	evt.initEvent("focusout", false, true);
    
}

function logInfo(text){
    console.log(text);
}

function addIcoColor(isDev, hoststr){
    let hostAddr = hoststr.split(' ')[1];
    const options = {'env':isDev?'dev':'pro', 'host':hostAddr, 'color':isDev?'#2196f3':'#f44336'}
    chrome.storage.sync.set({options}, () => {
        logInfo(options);
    })
}

const script = document.createElement('script');
script.setAttribute('type', 'text/javascript');
script.setAttribute('src', chrome.runtime.getURL('reqModify.js'));
document.documentElement.appendChild(script);